// 封装通用请求函数
import { config, getApiUrl } from '../constant/index';

// 模拟数据池
const mockData = {
  // 登录相关模拟数据
  '/logon/login': {
    success: true,
    data: {
      token: 'mock-token-123456',
      userInfo: {
        id: '1',
        nickname: '星球访客',
        avatar: '/static/logo.png',
        planetId: 'earth'
      }
    },
    message: '登录成功'
  },
  '/logon/register': {
    success: true,
    data: {
      token: 'mock-token-654321',
      userInfo: {
        id: '2',
        nickname: '新访客',
        avatar: '/static/logo.png',
        planetId: 'mars'
      }
    },
    message: '注册成功'
  },
  // PLUS会员相关模拟数据
  '/plus-member/info': {
    success: true,
    data: {
      isMember: false,
      memberType: '',
      startDate: '',
      expiryDate: '',
      daysLeft: 0,
      diamonds: 100,
      benefits: [
        { id: 1, name: '每天领星钻', desc: '每天可领取10颗星钻' },
        { id: 2, name: '免广告', desc: '无广告打扰，纯净体验' },
        { id: 3, name: '无限制匹配', desc: '匹配次数不受限制' }
      ]
    },
    message: '获取会员信息成功'
  },
  // 购买星钻模拟数据
  '/plus-member/diamonds/purchase': {
    success: true,
    data: {
      orderId: 'diamond-order-' + Date.now(),
      diamonds: 50,
      bonus: 5,
      totalDiamonds: 55,
      price: 5,
      transactionTime: new Date().toISOString()
    },
    message: '星钻购买成功'
  },
  '/plus-member/purchase': {
    success: true,
    data: {
      orderId: 'order-' + Date.now(),
      memberType: 'monthly',
      duration: 30,
      amount: 11.99,
      startDate: new Date().toISOString(),
      expiryDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString()
    },
    message: '购买成功'
  },
  '/plus-member/history': {
    success: true,
    data: [
      {
        id: 'history-1',
        memberType: '30天会员',
        duration: 30,
        amount: 11.99,
        purchaseDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
        status: 'expired'
      },
      {
        id: 'history-2',
        memberType: '90天会员',
        duration: 90,
        amount: 21.99,
        purchaseDate: new Date(Date.now() - 180 * 24 * 60 * 60 * 1000).toISOString(),
        status: 'expired'
      }
    ],
    message: '获取购买历史成功'
  },
  // 续订会员模拟数据
  '/plus-member/renew': {
    success: true,
    data: {
      orderId: 'order-renew-' + Date.now(),
      memberType: 'monthly',
      duration: 30,
      amount: 11.99,
      startDate: new Date().toISOString(),
      expiryDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString()
    },
    message: '续订成功'
  },
  // 取消会员模拟数据
  '/plus-member/cancel': {
    success: true,
    data: {
      isMember: false,
      status: 'cancelled'
    },
    message: '会员已取消'
  },
  // 获取会员权益详情模拟数据
  '/plus-member/benefits': {
    success: true,
    data: [
      {
        id: 1,
        name: '每日星钻',
        desc: '每天可领取10颗星钻',
        icon: '💎',
        value: '10/天'
      },
      {
        id: 2,
        name: '免广告特权',
        desc: '无广告打扰，纯净体验',
        icon: '🚫',
        value: '永久'
      },
      {
        id: 3,
        name: '无限匹配',
        desc: '匹配次数不受限制',
        icon: '🔄',
        value: '无限次'
      },
      {
        id: 4,
        name: '专属标识',
        desc: '个人主页显示会员徽章',
        icon: '👑',
        value: '专属'
      },
      {
        id: 5,
        name: '优先推送',
        desc: '消息优先推送',
        icon: '📢',
        value: '高级'
      }
    ],
    message: '获取会员权益成功'
  },
  // 漂流瓶相关模拟数据
  '/bottle/pick': {
    success: true,
    data: {
      id: 'bottle-1',
      content: '来自地球的问候，愿宇宙和平！',
      from: '地球访客',
      planet: 'earth',
      time: new Date().toISOString(),
      hasRespond: false
    },
    message: '捞取成功'
  },
  '/bottle/throw': {
    success: true,
    data: {
      id: 'bottle-new',
      time: new Date().toISOString()
    },
    message: '投放成功'
  },
  '/bottle/my': {
    success: true,
    data: [
      {
        id: 'bottle-2',
        content: '我在火星上留下了我的思念',
        time: new Date(Date.now() - 86400000).toISOString(),
        hasRespond: true,
        respondCount: 2
      },
      {
        id: 'bottle-3',
        content: '希望有人能收到我的消息',
        time: new Date(Date.now() - 172800000).toISOString(),
        hasRespond: false,
        respondCount: 0
      }
    ],
    message: '获取成功'
  },
  // 星球相关模拟数据
  '/planet/list': {
    success: true,
    data: [
      {
        id: 'earth',
        name: '地球',
        desc: '蓝色星球，生命的摇篮',
        visitors: 1024,
        image: '/static/earth.png'
      },
      {
        id: 'mars',
        name: '火星',
        desc: '红色星球，人类的下一站',
        visitors: 512,
        image: '/static/mars.png'
      },
      {
        id: 'jupiter',
        name: '木星',
        desc: '气态巨行星',
        visitors: 256,
        image: '/static/jupiter.png'
      }
    ],
    message: '获取成功'
  }
};

// 模拟请求延迟
const mockDelay = () => {
  return new Promise(resolve => {
    setTimeout(resolve, Math.random() * 1000 + 500);
  });
};

// 发送请求的基础方法
const request = async (options) => {
  const {
    url,
    method = 'GET',
    data = {},
    header = {},
    loading = true,
    toastError = true
  } = options;

  // 显示加载提示
  if (loading) {
    uni.showLoading({
      title: '加载中...',
      mask: true
    });
  }

  try {
    // 判断是否使用模拟数据
    if (config.useMockData) {
      await mockDelay();
      
      // 获取对应的模拟数据
      const mockResponse = mockData[url];
      
      if (mockResponse) {
        if (loading) {
          uni.hideLoading();
        }
        return mockResponse;
      } else {
        throw new Error('未找到对应的模拟数据');
      }
    }

    // 实际请求逻辑
    const response = await uni.request({
      url: getApiUrl(url),
      method,
      data,
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${uni.getStorageSync('token') || ''}`,
        ...header
      }
    });

    if (loading) {
      uni.hideLoading();
    }

    // 处理响应
    const [err, res] = response;
    if (err) {
      throw err;
    }

    if (res.statusCode === 200) {
      return res.data;
    } else {
      throw new Error(`请求失败：${res.statusCode}`);
    }
  } catch (error) {
    if (loading) {
      uni.hideLoading();
    }

    if (toastError) {
      uni.showToast({
        title: error.message || '网络请求失败',
        icon: 'none'
      });
    }

    throw error;
  }
};

// GET请求
export const get = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'GET',
    data,
    ...options
  });
};

// POST请求
export const post = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  });
};

// PUT请求
export const put = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    ...options
  });
};

// DELETE请求
export const del = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'DELETE',
    data,
    ...options
  });
};

export default {
  request,
  get,
  post,
  put,
  del
};